﻿using System;
using System.Collections.Generic;
using System.Linq;

using System.Web.Mvc;

namespace CommonLibrary.Web.Core
{
    public class EntityController<T> : Controller where T : class
    {
        /// <summary>
        /// Returns the default entity service class for this type of entity.
        /// </summary>
        /// <returns></returns>
        public virtual EntityService<T> GetService()
        {
            var service = EntityFactory.GetEntityService<T>();
            return service;
        }


        /// <summary>
        /// Handler for the create action ( shows new item )
        /// </summary>
        /// <returns></returns>
        public virtual ActionResult Create()
        {
            return View();
        }


        /// <summary>
        /// Handler for the create action when entity fields are filled out.
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public virtual ActionResult Create(T item)
        {
            var service = GetService();
            service.Create(item);
            return View(item);
        }


        /// <summary>
        /// Default handler for the update action when entity fields are updated
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public virtual ActionResult Update(T item)
        {
            var service = GetService();
            service.Update(item);
            return View();
        }


        /// <summary>
        /// Default handler for the index action.
        /// </summary>
        /// <returns></returns>
        public virtual ActionResult Index()
        {
            var service = GetService();
            var items = service.GetAll();
            return View();
        }


        /// <summary>
        /// Default handler for the delete action.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public virtual ActionResult Delete(int id)
        {
            var service = GetService();
            service.Delete(id);
            return View();
        }
    }
}
